/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.glide.adapter;

import com.bumptech.glide.Glide;
import com.example.glide.model.Model;
import com.example.glide.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;

public class ModelBaseAdapter extends BaseItemProvider {

    private Context context;
    private List<Model> Modeles;


    public ModelBaseAdapter(Context context, List<Model> Modeles) {
        this.context = context;
        this.Modeles = Modeles;
    }

    @Override
    public int getCount() {
        return Modeles.size();
    }

    @Override
    public Object getItem(int i)
    {
        return Modeles.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Model model = Modeles.get(i);
        Text itemName;
        Image itemAvatar;
        Component container = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_hero, null, false);
        itemAvatar = (Image) container.findComponentById(ResourceTable.Id_item_avatar);
        itemName = (Text) container.findComponentById(ResourceTable.Id_item_name);
        itemName.setText(model.text);
        refreshImageView(itemAvatar,model);
        return container;
    }

    private void refreshImageView(Image aiv, Model model){
        if(aiv == null){
            return;
        }

        Glide.with(context)
                .asDrawable()
                .load(model.url)
                .placeholder(ResourceTable.Media_tiger)
                .centerCrop()
                .circleCrop()
                .into(aiv);
    }
}
